<script setup lang="ts">
  import {reactive, ref} from 'vue'
  import {useRouter} from "vue-router";
  import {Users} from "../../api/users.ts";
  import {ElMessage, FormInstance, FormRules} from "element-plus";
  import Header from "../../components/Header.vue";
  import {useUserStore} from "../../store/users.ts";
  
  const router = useRouter()
  const userStore = useUserStore()
  
  
  //当前登录模式
  const type = ref("密码登录")
  
  //表单正则
  const reg = {
    email: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/,
    password: /[0-9A-Za-z]{8,16}/,
    code: /^[a-zA-Z0-9]{6}$/
  }
  
  //登录表单
  const form = reactive({
    email: "",
    password: "",
    code: ""
  })
  
  
  //验证邮箱
  const ruleFormRef = ref<FormInstance>()
  const validateEmail = (_: any, value: any, callback: any) => {
    if (value === '') {
      callback(new Error('请填写邮箱'))
    } else if (!reg.email.test(value)) {
      callback(new Error('邮箱地址格式不正确'))
    } else {
      if (form.email !== '') {
        if (!ruleFormRef.value) return
      }
      callback()
    }
  }
  
  //验证密码
  const validatePassword = (_: any, value: any, callback: any) => {
    if (value === '') {
      callback(new Error('请输入密码'))
    } else if (!reg.password.test(value)) {
      callback(new Error('密码需以字母开头、长度8~16位的字母、数字、下划线组成'))
    } else {
      callback()
    }
  }
  
  // 验证验证码
  const validateCode = (_: any, value: any, callback: any) => {
    if (value.length !== 6) {
      return callback(new Error('请输入6位验证码'))
    }
  }
  
  // 总体验证规则
  const rules = reactive<FormRules<typeof form>>({
    email: [{validator: validateEmail, trigger: 'blur'}],
    password: [{validator: validatePassword, trigger: 'blur'}],
    code: [{validator: validateCode, trigger: 'blur'}],
  })
  
  
  //登录
  const login = (formEl: any | undefined) => {
    if (type.value === "密码登录") {
      if (!formEl) return
      formEl.validate((valid: any) => {
        if (valid) {
          Users["loginByPassword"](form).then((res: any) => {
            userStore.SET_USER(res.data)
            router.push("/")
          })
        } else {
          console.log('error submit!')
          return false
        }
      })
    }
    if (type.value === "验证码登录") {
      Users["loginByCode"](form).then((res: any) => {
        userStore.SET_USER(res.data)
        router.push("/")
      })
    }
  }
  
  //成功获取验证码后，按钮进入倒计时
  const gotCode = ref(false)
  const time = ref(60)
  
  //获取验证码
  const getCode = () => {
    console.log(reg.email.test(form.email))
    console.log(form.email)
    if (!reg.email.test(form.email)) return
    Users["getCode"](form.email).then((res: any) => {
      console.log(res)
      if (res.code == 200) {
        gotCode.value = true
        ElMessage({
          message: "请前往邮箱查看验证码",
          type: 'success'
        })
      }
      let timer = setInterval(() => {
        time.value -= 1
        if (time.value == 0) {
          gotCode.value = false
          time.value = 60
          clearInterval(timer)
        }
      }, 1000)
    })
  }


</script>

<template>
  <div class="box">
    <Header></Header>
    <div class="form">
      <div class="choose-type">
        <el-radio-group v-model="type">
          <el-radio-button label="密码登录"/>
          <el-radio-button label="验证码登录"/>
        </el-radio-group>
      </div>
      <el-form
          ref="ruleFormRef"
          :model="form"
          :rules="rules"
          status-icon
          label-width="120px"
          label-position="top"
          class="demo-ruleForm"
      >
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="form.email" type="text" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="密码" v-if="type==='密码登录'" prop="password">
          <el-input v-model="form.password" type="password" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="验证码" prop="code" v-else>
          <el-input v-model="form.code" autocomplete="off">
            <template #append>
              <div>
                <el-button style="width: 120px;" :plain="true" type="primary" @click="getCode"
                    :disabled="gotCode" autofocus>{{ gotCode ? time : "获取验证码" }}
                </el-button>
              </div>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login(ruleFormRef)" class="submit">
            登录
          </el-button>
        </el-form-item>
        <el-form-item>
          <div class="btns">
            <el-button link type="primary" @click="router.push('/forget')">
              忘记密码
            </el-button>
            <el-button link type="primary" @click="router.push('/regist')">
              注册
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  
  </div>
</template>

<style scoped lang="scss">
  .box {
    .form {
      width: 25%;
      height: 350px;
      padding: 50px 100px 0;
      position: fixed;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
      border-radius: 15px;
      box-shadow: 0 0 20px 1px rgba(0, 0, 0, 0.1);
      
      .el-input-group__append {
        background: #409eff !important;
        color: #fff !important;
      }
      
      .choose-type {
        width: 100%;
        text-align: center;
        margin-bottom: 20px;
      }
      
      .btns {
        width: 100%;
        display: flex;
        justify-content: space-evenly;
      }
      
      .submit {
        width: 100%;
        height: 40px;
        margin-top: 20px;
      }
    }
  }


</style>